package service

import (
	"community-service/internal/app/config"
	"community-service/internal/app/entity"
	"community-service/internal/app/schema"
	"community-service/pkg/error"
	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context, su schema.User) {
	var eu entity.User
	result1 := config.MYSQLDB.Table("users").Where("post = ?", su.Post).First(&eu)
	if result1.Error != nil {
		result2 := Register(c, su)
		if !result2 {
			error.Response(c, error.BadRequest, gin.H{}, "用户注册失败！")
			return
		}

		Login(c, su)
		return
	}

	if !(eu.Name == su.Name) {
		error.Response(c, error.BadRequest, gin.H{}, "用户信息有误！")
		return
	}

	error.Response(c, error.OK, gin.H{"id": eu.ID}, "登陆成功！")
}

func Register(c *gin.Context, su schema.User) bool {
	var eu entity.User
	eu.Name = su.Name
	eu.Age = su.Age
	eu.Phone = su.Phone
	eu.Post = su.Post

	result := config.MYSQLDB.Table("users").Create(&eu)
	if result.Error != nil {
		error.Response(c, error.BadRequest, gin.H{}, "用户注册失败！")
		return false
	}

	return true
}
